package com.hmdp.redis;

import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
@RequiredArgsConstructor
public class RedisIdWrok {

    private static final long BEGING_TIMESTAMP=1748304000;
    private static final long COUNT_BITS=32;

    private final StringRedisTemplate stringRedisTemplate;

    public long nextId(String keyPrefix){
        //生成时间戳
        long now = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
        long timeStamp=now-BEGING_TIMESTAMP;
        //使用redis自增长
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy:MM:dd");
        LocalDate today = LocalDate.now();
        String date = today.format(dateTimeFormatter);
        long conut = stringRedisTemplate.opsForValue().increment("icr" + keyPrefix + ":" + date);

        return timeStamp<<COUNT_BITS | conut;
    }

    public static void main(String[] args) {
        LocalDateTime localDateTime = LocalDateTime.of(2025, 5, 27, 0, 0, 0, 0);
        long epochSecond = localDateTime.toEpochSecond(ZoneOffset.UTC);


        System.out.println(epochSecond);
    }
}
